package com.yue.yadmin.shiro.filter;

import java.util.List;

import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.yue.yadmin.model.SysMenu;
import com.yue.yadmin.service.SysMenuService;
import com.yue.yadmin.service.SysUserSerivce;
import com.yue.yadmin.utils.Log;

/**
 * 动态权限管理
 * @author liaoxinyue
 * 2018年7月10日 下午4:27:46
 *
 */
public class DynamicPermissionsFilterFactory extends ShiroFilterFactoryBean {
	
    private String configDefinitions;  
      
    @Autowired
	private SysMenuService sysMenuService;
    @Autowired
    private SysUserSerivce sysUserSerivce;
    
//    @Autowired
//    private AccountRealm userRealm;

//    /**
//     * 更新权限相关数据后,需要主动调用该方法
//     * @author zhaohao
//     * 2018年1月14日 下午7:42:11
//     */
//    public void updateFilterChain() {
//        synchronized (this) {   //强制同步，控制线程安全
//            AbstractShiroFilter shiroFilter = null;
//            try {
//                shiroFilter = (AbstractShiroFilter) this.getObject();
//
//                PathMatchingFilterChainResolver resolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
//                // 过滤管理器
//                DefaultFilterChainManager manager = (DefaultFilterChainManager) resolver.getFilterChainManager();
//                // 清除权限配置
//                manager.getFilterChains().clear();
//                this.getFilterChainDefinitionMap().clear();
//                // 重新设置权限
//                this.setFilterChainDefinitions(configDefinitions);//传入配置中的filterchains
//
//                Map<String, String> chains = this.getFilterChainDefinitionMap();
//                //重新生成过滤链
//                if (!CollectionUtils.isEmpty(chains)) {
//                    chains.forEach((url, definitionChains) -> {
//                        manager.createChain(url, definitionChains.trim().replace(" ", ""));
//                    });
//                }
//                userRealm.clearAllAuth();
//            } catch (Exception e) {
//            	logger.error(e.getMessage(), e);
//            }
//        }
//    }
    
  
    @Override  
    public void setFilterChainDefinitions(String definitions) {
    	if(configDefinitions == null){
    		configDefinitions = definitions;
    	}
		Ini ini = new Ini();
		ini.load(configDefinitions);
		Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
		if (CollectionUtils.isEmpty(section)) {
			section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		}
		Log.getLogger(this).debug("default section:{}",section);
        List<SysMenu> sysMenus = sysMenuService.getPermissionMenus();
        for(int i=0,total=sysMenus.size();i<total;i++){
        	SysMenu sysMenu = sysMenus.get(i);
        	section.put(sysMenu.getUrl(), "perms["+sysMenu.getPermission()+"]");
        }
        if(section.containsKey("/**")){
        	String str = section.get("/**");
        	section.remove("/**");
        	section.put("/**", str);
        }
        Log.getLogger(this).debug("after section:{}",section);
        setFilterChainDefinitionMap(section);
        //更新admin角色权限
        sysUserSerivce.updateAdminRolePerm(sysMenus);
    }
	
}
